package com.zjcode.cdcer.utils;

import com.chinatechstar.component.commons.utils.StringUtils;
import com.chinatechstar.component.commons.utils.UuidUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Date;
import java.util.Objects;

/**
 * 文件上传工具类
 * 
 * @author bqyang
 */
public class FileUploadUtils
{

    private static Logger log = LoggerFactory.getLogger(FileUploadUtils.class);

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;


    /**
     * 文件上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @return 返回上传成功的文件名
     * @throws IOException 比如读写文件出错时
     */
    public static final String upload(String baseDir, MultipartFile file) throws IOException
    {
        int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
        {
            return "";
        }

        String fileName = extractFilename(file);

        String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
        file.transferTo(Paths.get(absPath));
        return getPathFileName(fileName);
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file)
    {
        // 日期路径 即年/月/日 如2018/08/08
        String datePath = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
        return StringUtils.format("{}/{}.{}", datePath,
                UuidUtil.get32UUID(), getExtension(file));
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file)
    {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (org.apache.commons.lang3.StringUtils.isEmpty(extension))
        {
            extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }

    public static final String getNewFile()
    {
        // 日期路径 即年/月/日 如2018/08/08
        String datePath = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
        return StringUtils.format("{}/{}.{}", datePath,
                UuidUtil.get32UUID(), "pdf");
    }

    public static final String getImageFile() {
        String datePath = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
        String imageFile = StringUtils.format("{}/{}.{}", datePath,
                UuidUtil.get32UUID(), "png");

        return imageFile;
    }

    /**
     * 描述：将base64图片解码并保存
     */
    public static File decodeBase64ToImage(String base64, String path, String imageFile) {
        File file = null;
        try {
            file = new File(path + imageFile);
            if ( !file.getParentFile().exists()) {
                file.mkdirs();
            }

            String[] baseStrs = base64.split(",");
            byte[] imageBytes = Base64.getMimeDecoder().decode(baseStrs[1]);

            ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
            BufferedImage image = ImageIO.read(bis);
            bis.close();

            ImageIO.write(image, "png", file);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static final void removeFile(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        boolean deleted = Files.deleteIfExists(path);
        if (deleted) {
            log.info("文件删除成功");
        } else {
            log.error("文件不存在或删除失败");
        }
    }

    private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
    {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
    }

    private static final String getPathFileName(String fileName) throws IOException
    {
        String pathFileName = "/" + fileName;
        return pathFileName;
    }

}